﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using BlackBird.Models;
using BlackBird.DataAccess;

namespace BlackBird.ControllerHelpers
{
	public class EventsHelper
	{
		#region Plan
		public static Dictionary<string, List<PlanViewItemDM>> GetProjectPlanView(string ParentId)
		{
			Dictionary<string, List<PlanViewItemDM>> ret = new Dictionary<string, List<PlanViewItemDM>>();

			List<@event> projectAllEvents = EventsDataAccess.GetAllEventsByProjectId(int.Parse(ParentId));

			foreach (var et in projectAllEvents)
			{
				string key = ((DateTime)(et.Date)).ToString("yyyy-MM-dd");
				if (!ret.Keys.Contains(key))
				{
					List<PlanViewItemDM> items1 = new List<PlanViewItemDM>();
					ret.Add(key,items1);
				}

				var item = ConvertFromEventToPlanViewItemDm(et);

				ret[key].Add(item);
			}			



			//添加今天作为时间轴
			if (!ret.ContainsKey(DateTime.Now.ToString("yyyy-MM-dd")))
			{
				List<PlanViewItemDM> itemstoday = new List<PlanViewItemDM>();
				ret.Add(DateTime.Now.ToString("yyyy-MM-dd"), itemstoday);
			}

			var orderEnumer = ret.OrderBy(v => v.Key, new PlanDateCompare());

			return orderEnumer.ToDictionary<KeyValuePair<string, List<PlanViewItemDM>>, string, List<PlanViewItemDM>>(p => p.Key, p => p.Value);

		}

		public static PlanViewItemDM ConvertFromEventToPlanViewItemDm(@event evt)
		{
			PlanViewItemDM pDm = new PlanViewItemDM();
			pDm.Id = evt.idEvent.ToString();
			pDm.ParentId = evt.idProject.ToString();
			pDm.FinishTime = (DateTime)(evt.Date);

			pDm.Name = evt.Name;
			pDm.type = CommonDataAccess.GetSupportTypesById((int)evt.idEventType);
			pDm.Status = CommonDataAccess.GetSupportTypeStatusById((int)evt.idStatus);
			pDm.Comment = evt.Comments;

			return pDm;
		}

		public class PlanDateCompare : IComparer<string>
		{
			// Because the class implements IComparer, it must define a 
			// Compare method. The method returns a signed integer that indicates 
			// whether s1 > s2 (return is greater than 0), s1 < s2 (return is negative),
			// or s1 equals s2 (return value is 0). This Compare method compares strings. 
			public int Compare(string s1, string s2)
			{
				DateTime dt1 = DateTime.Parse(s1);
				DateTime dt2 = DateTime.Parse(s2);
				return DateTime.Compare(dt1, dt2);
			}
		}
		#endregion
	}
}